(function($){

    $.fn.extend({
        freetextsearch : function(options, arg) {
            if (typeof(options) == "object") {
                options = $.extend({}, $.freetextsearch.defaults, options);
            }
            this.each(function() {

                for (var fld in options) {
                    if (typeof(options[fld]) == "function") { continue; }
                    jQuery(this).attr("plugin_ft_" + fld, options[fld]);
                }
                new $.freetextsearch(this, options, arg);
            });
            return;
        }
    });

    $.freetextsearch = function(item, options, arg) {
        var myName = item.name;
        var pos = jQuery(item).offset();
        var dropdown = jQuery("<select>")
            .attr("id", myName + "_list")
            .attr("size", 6)
            .addClass("company_select")
            .css({
                height : "140px",
                position : "absolute",
                height : "130px",
                width : "300px",
                zIndex : 100
            })
            .hide()
            .change(function() {
                jQuery(item).val(jQuery(this).find("option:selected").text());
                jQuery(this).hide("fade", {}, 300);
            })
        ;
        jQuery("body").append(dropdown);
        jQuery("body").click(function(ev) {
            if (ev.target.tagName != "SELECT") {
                dropdown.hide("fade", {}, 300);
            }
        });

        var hideList = function() {
            jQuery("select.freetextsearch").hide("fade", {}, 300);
        }

        if (typeof(options) == "string") {
            var methodName = options;
            options = {};
            for (var fld in $.freetextsearch.defaults) {
                options[fld] = jQuery(item).attr("plugin_ft_" + fld);
            }
            if (methodName == "closelist") {
                jQuery("select.company_select").hide("fade", {}, 300);
            }
            // methods
        } else {
            if (jQuery(item).val() == "") {
                jQuery(item).val(options.defaulttext);
                jQuery(item).removeClass("textentered");
            } else {
                jQuery(item).addClass("textentered");
            }
            var timeout;
            jQuery(item).focus(function() {
                if (this.value == options.defaulttext) {
                    this.value = "";
                }
                if (options.emptyOnFocus) {
                    this.value = "";
                }
            });
            jQuery(item).keyup(function(e) {
                if (!jQuery(this).hasClass("textentered")) {
                    jQuery(this).addClass("textentered");
                }
                var code = (e.keyCode ? e.keyCode : e.which);
                if (options.enterHandler != null && code == 13) {
                    return false;
                }
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = null;
                }
                timeout = setTimeout(function() {
                    var dependantValue = null;
                    if (options.dependantControl) {
                        dependantValue = options.dependantControl.val() == "Please select" ? "" : options.dependantControl.val();
                    }
                    callService(options.sourcepage, options.filterservice, {
                        searchtext : jQuery(item).val(),
                        dependant : dependantValue
                    }, {
                        success : function(result) {
                            dropdown
                                .css({
                                    position : "absolute",
                                    top : pos.top + 25,
                                    left : pos.left - 5
                                })
                            ;
                            dropdown.empty();
                            for (var i = 0; i<result.items.length; i++) {
                                dropdown.append(jQuery("<option>")
                                    .text(result.items[i].companyname)
                                    .val(result.items[i].company_id)
                                );
                            }
                            dropdown.show("fade", {}, 300);
                            if (options.change) {
                                options.change();
                            }
                        }
                    });
                }, 800);
            });
            jQuery("img[ref='" + myName + "'][func='search']").click(function() {
                redirect(options.resultpage, options.resultsubpage, {
                    selectedItem : dropdown.find("option:selected").val()
                }, true);
            });
        }

        $.freetextsearch.defaults = {
            dependantControl : null,
            page : "",
            filterservice : "getlike",
            change : null,
            sourcepage : "",
            resultpage : "",
            resultsubpage : "",
            defaulttext : "",
            emptyOnFocus : false
        }
    }
})(jQuery);

jQuery(window).click(function(e) {
    var ev = (e ? e : window.event);
    var element = (ev.target ? ev.target : ev.srcElement);
    if (!jQuery(element).hasClass("freetextsearch")) {
        jQuery("select.freetextsearch").hide("fade", {}, 300);
    }
});
